package xin.fsqr520.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import xin.fsqr520.project.domain.constants.MessageConstant;
import xin.fsqr520.project.domain.po.BaseException;
import xin.fsqr520.project.domain.po.User;
import xin.fsqr520.project.domain.vo.Result;
import xin.fsqr520.project.mapper.UserMapper;
import xin.fsqr520.project.service.IUserService;
import xin.fsqr520.project.util.EncodingUtil;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(String phoneNumber, String password) {
        // 参数校验
        if (StringUtils.isAnyBlank(phoneNumber, password)) {
            throw new BaseException(MessageConstant.PHONENUMBER_PASSWORD_NOT_NULL);
        }

        // 构建查询条件
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>()
                .eq(User::getPhoneNumber, phoneNumber)
                .eq(User::getPassword, EncodingUtil.encode(password));

        User user = userMapper.selectOne(wrapper);
        if (user == null) throw new BaseException(MessageConstant.PHONENUMBER_PASSWORD_ERROR);
        else return user;
    }

    @Override
    public int register(String phoneNumber, String username, String password) {
        // 3.1 校验手机号是否已注册
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        //判断手机号有没有
        wrapper.eq(User::getPhoneNumber, phoneNumber);
        if (this.count(wrapper) > 0) {//this调用ServiceImpl中的方法
            throw new BaseException("手机号已存在");
        }

        // 3.2 校验用户名是否已存在
        wrapper.clear();
        wrapper.eq(User::getUsername, username);
        if (this.count(wrapper) > 0) {
            throw new BaseException("用户名已存在");
        }

        // 4. 密码加密 使用md5对密码加密
        password = EncodingUtil.encode(password);

        // 5. 构建用户实体
        User user = User.builder()
                .username(username)
                .password(password) // 存储加密后的密码
                .phoneNumber(phoneNumber)
//                .createTime(LocalDateTime.now())//数据库会自己处理
//                .updateTime(LocalDateTime.now())
                .build();

        // 6. 保存用户信息到数据库
        return userMapper.insert(user);

    }


}
